// pages/student/mall/mall.js
import { products } from '../../../utils/mockData.js'

Page({
  data: {
    searchQuery: '',
    currentCategory: 0,
    categories: [
      { id: 0, name: '全部' },
      { id: 1, name: '教材教辅' },
      { id: 2, name: '技术书籍' },
      { id: 3, name: '学习资料' },
      { id: 4, name: '电子课件' }
    ],
    bannerProducts: [],
    recommendProducts: [],
    hotProducts: [],
    allProducts: [],
    sortType: 'default' // default, price_asc, price_desc, sales
  },
  onLoad() {
    this.loadData()
  },
  loadData() {
    const recommendProducts = products.filter(p => p.is_recommended)
    const hotProducts = products.sort((a, b) => b.sales_count - a.sales_count)
    
    this.setData({
      bannerProducts: products.slice(0, 3),
      recommendProducts: recommendProducts,
      hotProducts: hotProducts,
      allProducts: products
    })
  },
  onSearchInput(e) {
    this.setData({
      searchQuery: e.detail.value
    })
  },
  onSearch() {
    const { searchQuery } = this.data
    wx.showToast({
      title: `搜索: ${searchQuery}`,
      icon: 'none'
    })
  },
  switchCategory(e) {
    const categoryId = e.currentTarget.dataset.id
    this.setData({
      currentCategory: categoryId
    })
  },
  changeSort(e) {
    const sortType = e.currentTarget.dataset.type
    let sortedProducts = [...this.data.allProducts]
    
    switch(sortType) {
      case 'price_asc':
        sortedProducts.sort((a, b) => a.price - b.price)
        break
      case 'price_desc':
        sortedProducts.sort((a, b) => b.price - a.price)
        break
      case 'sales':
        sortedProducts.sort((a, b) => b.sales_count - a.sales_count)
        break
    }
    
    this.setData({
      sortType,
      allProducts: sortedProducts
    })
  },
  goToBookDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/student/book-detail/book-detail?id=${id}`
    })
  },
  addToCart(e) {
    const id = e.currentTarget.dataset.id
    wx.showToast({
      title: '已加入购物车',
      icon: 'success'
    })
  },
  onPullDownRefresh() {
    this.loadData()
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 1000)
  }
})
